import 'dart:convert';
import 'dart:io' show Platform;
import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:family_app/src/common/constants.dart';
import 'package:family_app/src/features/auth/models/user_model.dart';
import 'package:family_app/src/features/auth/models/login_param.dart';

/// 身份验证服务提供者
final authServiceProvider = Provider<AuthService>((ref) {
  // 统一使用 10.0.2.2:9092 作为基础 API URL
  final String baseUrl = 'http://10.0.2.2:9092';

  final dio = Dio(BaseOptions(
    baseUrl: baseUrl,
    connectTimeout: const Duration(seconds: 5),
    receiveTimeout: const Duration(seconds: 30),
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    },
  ));
  
  // 添加日志拦截器，方便调试
  dio.interceptors.add(LogInterceptor(
    requestBody: true,
    responseBody: true,
  ));
  
  return AuthService(dio);
});

/// 身份验证服务
class AuthService {
  final Dio _dio;
  final _userBox = Hive.box(AppConstants.userBox);

  AuthService(this._dio);

  /// 发送验证码
  Future<bool> sendVerificationCode(String phone) async {
    try {
      // 发送验证码请求
      final response = await _dio.post('/auth/send-code', data: {'phone': phone});
      return response.statusCode == 200;
    } catch (e) {
      print('发送验证码失败: $e');
      // 如果API不可用，使用模拟数据
      await Future.delayed(const Duration(seconds: 1));
      return true;
    }
  }

  /// 手机号验证码登录
  Future<UserModel?> loginWithPhone(String phone, String code) async {
    try {
      // 发送登录请求
      final response = await _dio.post('/auth/login/phone', data: {
        'phone': phone,
        'code': code,
      });
      
      if (response.statusCode == 200 && response.data['code'] == 200) {
        final userData = response.data['data'];
        final user = UserModel.fromJson(userData);
        
        // 保存用户信息和登录状态
        await _saveUserInfo(user);
        return user;
      }
      
      // 如果API不可用，使用模拟数据
      await Future.delayed(const Duration(seconds: 1));
      final user = UserModel(
        id: '1',
        name: '用户${phone.substring(phone.length - 4)}',
        phone: phone,
        avatar: null,
        createdAt: DateTime.now(),
      );

      // 保存用户信息和登录状态
      await _saveUserInfo(user);
      return user;
    } catch (e) {
      print('手机号验证码登录失败: $e');
      return null;
    }
  }
  
  /// 账号密码登录
  Future<UserModel?> loginWithPassword(String username, String password) async {
    try {
      // 调用后端登录接口
      final param = AccountLoginParam(
        account: username,
        password: password,
      );
      
      // 显式对请求体进行 JSON 字符串化，避免部分服务对分块传输或未知 Content-Length 处理异常
      final String body = jsonEncode(param.toJson());

      final response = await _dio.post(
        '/login/account',
        data: body,
        options: Options(
          headers: const {
            'Content-Type': 'application/json; charset=utf-8',
            // 某些网关/服务对长连接处理不当，强制关闭可避免悬挂
            'Connection': 'close',
          },
          // 针对此请求单独设置更宽松的超时，防止服务端处理略慢导致的误判
          receiveTimeout: Duration(seconds: 30),
          sendTimeout: Duration(seconds: 10),
        ),
      );
      
      // 解析响应数据
      if (response.statusCode == 200 && response.data['code'] == 200) {
        final loginResult = LoginResult.fromJson(response.data['data']);
        
        // 创建用户模型
        final user = UserModel(
          id: loginResult.id.toString(),
          name: loginResult.userName,
          email: username.contains('@') ? username : null,
          phone: username.length == 11 && int.tryParse(username) != null ? username : null,
          avatar: null,
          createdAt: DateTime.now(),
        );

        // 保存用户信息和登录状态
        await _saveUserInfo(user);
        // 保存token
        await _userBox.put(AppConstants.tokenKey, loginResult.token);
        
        return user;
      } else {
        // 登录失败
        return null;
      }
    } catch (e) {
      print('账号密码登录失败: $e');
      // 异常情况下，尝试使用模拟数据（仅用于开发测试）
      if (AppConstants.apiBaseUrl.contains('example.com')) {
        await Future.delayed(const Duration(seconds: 1));
        
        // 简单验证（仅用于演示）
        if (password.length < 6) {
          return null; // 密码错误
        }
        
        final user = UserModel(
          id: '3',
          name: username,
          email: username.contains('@') ? username : null,
          phone: username.length == 11 && int.tryParse(username) != null ? username : null,
          avatar: null,
          createdAt: DateTime.now(),
        );

        // 保存用户信息和登录状态
        await _saveUserInfo(user);
        return user;
      }
      return null;
    }
  }
  
  /// 验证滑块验证码
  Future<bool> verifyCaptcha(String token) async {
    try {
      // 模拟API请求验证滑块验证码
      final response = await _dio.post('/auth/verify-captcha', data: {
        'token': token,
      });
      return response.statusCode == 200;
    } catch (e) {
      print('验证滑块验证码失败: $e');
      // 如果API不可用，使用模拟数据
      await Future.delayed(const Duration(milliseconds: 500));
      return true;
    }
  }

  /// 微信登录
  Future<UserModel?> loginWithWeChat() async {
    try {
      // 模拟微信登录流程
      // 1. 调用微信SDK获取code
      // 2. 将code发送到服务器换取用户信息

      // 模拟成功响应
      await Future.delayed(const Duration(seconds: 1));
      final user = UserModel(
        id: '2',
        name: '微信用户',
        wxOpenId: 'wx_123456',
        avatar: null,
        createdAt: DateTime.now(),
      );

      // 保存用户信息和登录状态
      await _saveUserInfo(user);
      return user;
    } catch (e) {
      print('微信登录失败: $e');
      return null;
    }
  }

  /// 退出登录
  Future<bool> logout() async {
    try {
      // 清除本地存储的用户信息和登录状态
      await _userBox.delete('user');
      await _userBox.put('isLoggedIn', false);
      await _userBox.delete(AppConstants.tokenKey);
      return true;
    } catch (e) {
      print('退出登录失败: $e');
      return false;
    }
  }

  /// 获取当前登录用户
  UserModel? getCurrentUser() {
    try {
      final userData = _userBox.get('user');
      if (userData != null) {
        return UserModel.fromJson(Map<String, dynamic>.from(userData));
      }
      return null;
    } catch (e) {
      print('获取当前登录用户失败: $e');
      return null;
    }
  }
  
  /// 获取当前登录token
  String? getToken() {
    try {
      return _userBox.get(AppConstants.tokenKey);
    } catch (e) {
      print('获取当前登录token失败: $e');
      return null;
    }
  }

  /// 保存用户信息
  Future<void> _saveUserInfo(UserModel user) async {
    await _userBox.put('user', user.toJson());
    await _userBox.put('isLoggedIn', true);
  }
}
